<?php

namespace app\admin\controller\user;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\admin\model\User as ModelUser;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\pool\Sales;
use app\common\model\shop\Order;
use app\common\model\User as CommonModelUser;
use app\common\model\user\Alloca;
use app\common\model\user\Channel;
use app\common\model\user\Commission;
use app\common\model\user\Custom;
use app\common\model\user\Sale;
use Exception;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $acctLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $uids = AuthGroupAccess::where('group_id', 10)->column('uid');
        $adminlist = Admin::whereIn('id', $uids)->column('acct_id,nickname');
        $channllist = [0 => '无'] + Channel::column('id,name');
        $this->view->assign("acct_visible", $this->auth->acct_id == 0 ? true : false);
        $this->assignconfig("adminlist", $adminlist);
        $this->view->assign("channllist", $channllist);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $filter = $filter ? $filter : [];
            $map = [];
            if (isset($filter['puser.nickname']) && $filter['puser.nickname']) {
                $nickname = $filter['puser.nickname'];
                //待发货 待评价 待收货 已完成
                unset($filter['puser.nickname'], $op['puser.nickname']);
                $ids = ModelUser::whereLike('nickname', '%' . $nickname . '%')->column('id');
                //一定要有
                $this->request->get(['filter' => json_encode($filter)], ['op' => json_encode($op)]);
                $map['parent_id'] = ['in', $ids];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['lev'])
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->puser;
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->sales = Order::where('user_id', $v['id'])->where('status', '99')->sum('total_weight');
                $v->total_fee = Order::where('user_id', $v['id'])->where('status', '99')->sum('total_fee');
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('acct_id', $this->auth->acct_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }


        $result = false;
        Db::startTrans();
        try {
            $redis = Cache::store('redis')->handler();
            $cache_id = '1243:register_code_' . $params['mobile'];
            if (!$redis->setnx($cache_id, 1)) {
                exception('请勿重复提交');
            }
            $redis->expire($cache_id, 30);
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['code'] = generate_invite_code('user', 'code');

            $params['province_id'] = $params['province'];
            $params['city_id'] = $params['city'];
            $params['area_id'] = $params['area'];
            $acct = Admin::where('province',  $params['province'])->find();
            if (!$acct) {
                exception('该省份未绑定子平台');
            }
            $params['acct_id'] = $acct->acct_id;
            $params['city'] = db('cnarea')->where('area_code', $params['province'])->value('name') . '/' . db('cnarea')->where('area_code', $params['city'])->value('name') . '/' . db('cnarea')->where('area_code', $params['area'])->value('name');
            $result = $this->model->allowField(true)->save($params);
            queue('app\common\job\LockuserJob', $this->model->id, strtotime('+3 month') - time() + (strtotime(date('Y-m-d 23:59:59')) - time()), 'del_custom1243');

            Db::commit();
            $redis->del($cache_id);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $redis->del($cache_id);

            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $acct = Admin::where('province',  $params['province'])->find();
            if (!$acct) {
                exception('该省份未绑定子平台');
            }
            $params['acct_id'] = $acct->acct_id;
            $params['province_id'] = $params['province'];
            $params['city_id'] = $params['city'];
            $params['area_id'] = $params['area'];
            $params['city'] = db('cnarea')->where('area_code', $params['province'])->value('name') . '/' . db('cnarea')->where('area_code', $params['city'])->value('name') . '/' . db('cnarea')->where('area_code', $params['area'])->value('name');
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function cuser()
    {
        \think\Db::execute("SET @@sql_mode='';");
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $filter = $filter ? $filter : [];
            $map = [];

            if ($this->auth->acct_id) {
                $map['user.acct_id'] = $this->auth->acct_id;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (isset($filter['nickname']) && $filter['nickname']) {
                $this->model->whereLike('nickname', '%' . $filter['nickname'] . '%');
            }
            $list = $this->model
                ->with(['lev'])
                // ->where($where)
                ->where('is_channel', '1')

                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->puser;
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $uids = [];
                CommonModelUser::digui($v->id, $uids);
                $ucount = count($uids);
                if (isset($filter['jointime']) && $filter['jointime']) {
                    $arr = explode(' - ', $filter['jointime']);
                    $a = Commission::whereIn('user_id', $v->id)->where('status', '1')->where('type', 'channel')->where('createtime', 'between', [strtotime($arr[0]), strtotime($arr[1] . ' 23:59:59')])->field('source_price')->group('order_no')->select();
                    $ucount = CommonModelUser::whereIn('id', $uids)->where('createtime', 'between', [strtotime($arr[0]), strtotime($arr[1] . ' 23:59:59')])->count();
                } else {
                    $a = Commission::whereIn('user_id', $v->id)->where('status', '1')->where('type', 'channel')->field('source_price')->group('order_no')->select();
                }

                $v->xtotal = round(array_sum(array_column($a, 'source_price')), 2);
                $v->utotal = $ucount;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function suser()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $filter = $filter ? $filter : [];
            $map = [];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('is_channel', 1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->puser = ModelUser::get($v->channel);
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $total = Alloca::where('channel', $v->id)->count();
                $num = Alloca::where('channel', $v->id)->where('effective', '>=', 2000)->count();
                $v->proportion = $total > 0 ? bcmul($num / $total, 100, 0) : 0;

                $total_list = Custom::alias('c')->where('c.channel', $v->id)->field('id,(SELECT IF(sum(total_fee)>500,1,0) from fa_shop_order o where custom_id=c.custom_id and `status`>"0") as fee')->select();

                $total = count($total_list);
                $num = array_sum(array_column($total_list, 'fee')) ?? 0;

                //Order::where('custom_id', 'in', $custom_ids)->where('status', '>', 0)->count();
                $rate = $total > 0 ? bcmul($num / $total, 100, 0) : 0;

                $v->custom_proportion = $rate;
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function allocate($ids = null)
    {
        $user = $this->model->get($ids);
        if (!$user) {
            $this->error(__('经销商不存在'));
        }
        $total = Sale::where('is_pool', 1)->count();
        if ($total <= 0) {
            $this->error(__('没有可分配的销售'));
        }
        $num = Alloca::where('channel', $ids)->where('effective', '>=', 2000)->count();
        $proportion = $total > 0 ? bcmul($num / $total, 100, 0) : 0;
        if ($proportion <= 0) {
            $this->error(__('暂无分配名额1'));
        }
        $num = Sales::where('rate', '>=', $proportion)->where('rates', '<=', $proportion)->order('rate', 'asc')->value('num');
        if (!$num) {
            $this->error(__('暂无分配名额2'));
        }
        Db::startTrans();
        try {
            $uids = Alloca::where('acct_id', $this->auth->acct_id)->column('user_id');
            $list = ModelUser::where('is_pool', 1)->where('acct_id', $this->auth->acct_id)->whereNotIn('id', $uids)->limit($num)->orderRaw('rand()')->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $res = Alloca::create([
                    'user_id' => $v['id'],
                    'acct_id' => $v['acct_id'],
                    'channel' => $ids,
                ]);
                queue('app\common\job\Cancelalloca@cancelalloca', $res->id, 2 * 86400, 'cancelalloca1243');
                if ($res) {
                    $count++;
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return $e->getMessage();
        }
        if (!$count) {
            $this->error(__('未有新的销售可分配'));
        }
        $this->success('成功');
    }
    /**
     * 编辑
     */
    public function sedit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }
    function setagent($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //检查admin
        $has = Admin::where('mobile', $row['mobile'])->find();
        if ($has) {
            $this->error(__('手机号已存在管理员'));
        }
        Db::startTrans();
        try {
            $data = [
                'username' => $row['mobile'],
                'user_id' => $row['id'],
                'nickname' => $row['nickname'],
                'mobile' => $row['mobile'],
                'status' => 'normal',
            ];
            $admin = Admin::create($data);
            $dataset = [];
            // foreach ($group as $value) {
            $dataset[] = ['uid' => $admin->id, 'group_id' => 8];
            // }
            model('AuthGroupAccess')->saveAll($dataset);
            $row->is_agent = 1;
            $row->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            // throw $e;
            $this->error('添加失败');
        }
        $this->success();
    }

    function selectpage()
    {
        return parent::selectpage();
    }
}
